package com.cskaoyan.market.service.wx.impl;

import com.cskaoyan.market.db.domain.*;
import com.cskaoyan.market.db.mapper.*;
import com.cskaoyan.market.service.wx.WxCartService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName WxCartServiceImpl
 * @Description
 * @Author MZ
 * @Date 2023/5/21 18:08
 */
@Service
public class WxCartServiceImpl implements WxCartService {
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketGoodsMapper goodsMapper;
    @Autowired
    MarketGoodsProductMapper productMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketAddressMapper addressMapper;


    @Override
    public Map<String, Object> index(Integer userId) {
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> cartTotal = new HashMap<>();
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andDeletedEqualTo(false).andUserIdEqualTo(userId);
        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);
        // 初始化
        Integer goodsCount = 0;
        Integer checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedGoodsAmount = new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {

            Short number = marketCart.getNumber();
            goodsCount += number;
            goodsAmount = goodsAmount.add(marketCart.getPrice().multiply(BigDecimal.valueOf(number)));

            if (marketCart.getChecked()) {
                Short checkedNumber = marketCart.getNumber();
                checkedGoodsCount += checkedNumber;
                checkedGoodsAmount = checkedGoodsAmount.add(marketCart.getPrice().multiply(BigDecimal.valueOf(checkedNumber)));
            }
        }
        cartTotal.put("goodsCount", goodsCount);
        cartTotal.put("checkedGoodsCount", checkedGoodsCount);
        cartTotal.put("goodsAmount", goodsAmount.setScale(1));
        cartTotal.put("checkedGoodsAmount", checkedGoodsAmount.setScale(1));
        // 加入result
        result.put("cartTotal", cartTotal);

        result.put("cartList", marketCarts);

        return result;
    }

    @Override
    public Integer addCart(Integer productId, Integer goodsId, Short number) {
        MarketCart marketCart = new MarketCart();
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        marketCart.setUserId(userId);
        marketCart.setGoodsId(goodsId);
        marketCart.setGoodsSn(String.valueOf(goodsId));
        MarketGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        marketCart.setGoodsName(goods.getName());
        marketCart.setProductId(productId);
        MarketGoodsProduct product = productMapper.selectByPrimaryKey(productId);
        marketCart.setPrice(product.getPrice());
        marketCart.setNumber(number);
        marketCart.setSpecifications(product.getSpecifications());
        marketCart.setChecked(true);
        marketCart.setPicUrl(product.getUrl());
        marketCart.setAddTime(LocalDateTime.now());
        marketCart.setUpdateTime(LocalDateTime.now());
        marketCart.setDeleted(false);
        int row = cartMapper.insertSelective(marketCart);
        if (row != 1) {
            throw new IllegalArgumentException("参数错误");
        }
        return marketCart.getId();
    }

    @Override
    public Long getGoodsCount(Integer userId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        long count = cartMapper.countByExample(cartExample);

        return count;
    }

    @Override
    public void checked(Integer[] productIds, Boolean isChecked, Integer userId) {
        List<Integer> productIdList = Arrays.asList(productIds);
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andDeletedEqualTo(false).andProductIdIn(productIdList).andUserIdEqualTo(userId);
        MarketCart cart = new MarketCart();
        cart.setChecked(isChecked);
        cart.setUpdateTime(LocalDateTime.now());
        cartMapper.updateByExampleSelective(cart, cartExample);

    }

    @Override
    public MarketCart addfast(Integer productId, Integer goodsId, Short number, Integer userId) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andDeletedEqualTo(false).andProductIdEqualTo(productId).andGoodsIdEqualTo(goodsId).andNumberEqualTo(number).andUserIdEqualTo(userId);
        MarketCart marketCart = cartMapper.selectOneByExample(cartExample);

        return marketCart;
    }

    @Override
    public Map<String, Object> checkoutCart(Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId, Integer userId) {
        // cartId=0&addressId=23&couponId=0&userCouponId=-1&grouponRulesId=0
        Map<String, Object> result = new HashMap<>();
        result.put("grouponRulesId", grouponRulesId);
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andDeletedEqualTo(false).andCheckedEqualTo(true).andUserIdEqualTo(userId);
        // 获取订单总价
        // 配送费
        BigDecimal freightPrice = new BigDecimal(10);

        List<MarketCart> marketCarts = cartMapper.selectByExample(cartExample);
        BigDecimal actualPrice = new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            Short number = marketCart.getNumber();
            actualPrice = actualPrice.add(marketCart.getPrice().multiply(BigDecimal.valueOf(number)));

        }
        BigDecimal discount = new BigDecimal(0);
        if (couponId > 0 && userCouponId > 0){
            MarketCouponUser couponUser = couponUserMapper.selectByPrimaryKey(userCouponId);
            MarketCoupon marketCoupon = couponMapper.selectByPrimaryKey(couponId);
            BigDecimal min = marketCoupon.getMin();
            if (actualPrice.compareTo(min) >= 0) {
                discount = marketCoupon.getDiscount();
            }
        }

        result.put("actualPrice", actualPrice.add(freightPrice).subtract(discount));
        // 相同
        result.put("orderTotalPrice", actualPrice.add(freightPrice).subtract(discount));
        result.put("cartId", cartId);

        if (userCouponId == null) {
            result.put("userCouponId", -1);
        } else {
            result.put("userCouponId", userCouponId);
        }
        if (couponId == null) {
            result.put("couponId", -1);
        } else {
            result.put("couponId", couponId);
        }

        result.put("goodsTotalPrice", actualPrice);
        result.put("addressId", addressId);
        result.put("grouponPrice", 0);

        MarketAddress address = addressMapper.selectByPrimaryKey(addressId);
        result.put("checkedAddress", address);
        result.put("couponPrice", discount);

        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        couponUserExample.or().andDeletedEqualTo(false).andUserIdEqualTo(userId).andStatusEqualTo((short) 0);
        long availableCouponLength = couponUserMapper.countByExample(couponUserExample);
        result.put("availableCouponLength", availableCouponLength);


        result.put("freightPrice", freightPrice);

        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.or().andDeletedEqualTo(false).andCheckedEqualTo(true).andUserIdEqualTo(userId);
        List<MarketCart> checkedGoodsList = cartMapper.selectByExample(marketCartExample);
        result.put("checkedGoodsList", checkedGoodsList);

        return result;
    }

    @Override
    public int updateCart(Integer productId, Integer goodsId, Integer cartId, Short number) {

        MarketCart marketCart = new MarketCart();
        marketCart.setId(cartId);
        marketCart.setNumber(number);
        marketCart.setUpdateTime(LocalDateTime.now());

        int row = cartMapper.updateByPrimaryKeySelective(marketCart);

        return row;
    }

    @Override
    public void deleteCart(List<Integer> productIdsList) {
        MarketCartExample cartExample = new MarketCartExample();
        cartExample.or().andDeletedEqualTo(false).andProductIdIn(productIdsList);

        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);
        marketCart.setUpdateTime(LocalDateTime.now());

        cartMapper.updateByExampleSelective(marketCart, cartExample);

    }


}
